'use strict';

const Service = require('egg').Service;
class GisService extends Service {

    async getLocationByTagId(options) {
        const newTag = options.newTag;
        const ctx = this.ctx;
        let startDate = `${(new Date(options.startDate).getTime() + 1000 * 60 * 60 * 8) / 1000}`;
        let endDate = `${(new Date(options.endDate).getTime() + 1000 * 60 * 60 * 8) / 1000}`;
        const queryParams = {
            tagId: newTag.code,
            tsIn: {
                $gte: startDate,
                $lte: endDate
            }
        };

        let result = await ctx.model.Gis.find(queryParams).sort({
            tsIn: 1
        });
        let lastPoint = [];
        if (result.length == 0) {
            let lastPointRes = await ctx.model.Gis.find({
                tagId: newTag.code
            });
            if (lastPointRes.length == 0) {
                return [];
            }
            if (lastPointRes.length == 1) {
                let obj = lastPointRes[0];
                let tsIn = ctx.moment.utc(Number(obj.tsIn) * 1000).format('YYYY/MM/DD HH:mm:ss');
                let tsOut = ctx.moment.utc(Number(obj.tsOut) * 1000).format('YYYY/MM/DD HH:mm:ss');
                let residense = Number(obj.tsOut) - Number(obj.tsIn);
                let TrackLocations = {
                    tagId: obj.tagId,
                    devId: obj.devId,
                    latitude: obj.location[1],
                    longitude: obj.location[0],
                    address: obj.address,
                    inOut: obj.inOut,
                    tsIn: tsIn,
                    tsOut: tsOut,
                    residense: residense
                };
                return [{
                    id: 1,
                    TrackLocations: [TrackLocations]
                }];
            }
            lastPoint = await ctx.model.Gis.find({
                    tagId: newTag.code
                })
                .sort({
                    tsIn: -1
                })
                .limit(1);
            this.app.logger.debug(39, 'lastPoint', lastPoint);
            if (!lastPoint.length) {
                return [];
            }

            this.app.logger.debug(43, 'lastPoint', lastPoint);
            if (lastPoint.length) {
                let obj = lastPoint[0];
                let tsIn = ctx.moment.utc(Number(obj.tsIn) * 1000).format('YYYY/MM/DD HH:mm:ss');
                let tsOut = ctx.moment.utc(Number(obj.tsOut) * 1000).format('YYYY/MM/DD HH:mm:ss');
                let residense = Number(obj.tsOut) - Number(obj.tsIn);
                let TrackLocations = {
                    tagId: obj.tagId,
                    devId: obj.devId,
                    latitude: obj.location[1],
                    longitude: obj.location[0],
                    address: obj.address,
                    inOut: obj.inOut,
                    tsIn: tsIn,
                    tsOut: tsOut,
                    residense: residense
                };
                return [{
                    id: 1,
                    TrackLocations: [TrackLocations]
                }];
            }
        }

        console.log(16, queryParams);

        if (!result.length) {
            return lastPoint;
        }
        if (result.length == 1) {
            let obj = result[0];
            let tsIn = ctx.moment.utc(Number(obj.tsIn) * 1000).format('YYYY/MM/DD HH:mm:ss');
            let tsOut = ctx.moment.utc(Number(obj.tsOut) * 1000).format('YYYY/MM/DD HH:mm:ss');
            let residense = Number(obj.tsOut) - Number(obj.tsIn);
            let TrackLocations = {
                tagId: obj.tagId,
                devId: obj.devId,
                latitude: obj.location[1],
                longitude: obj.location[0],
                address: obj.address,
                inOut: obj.inOut,
                tsIn: tsIn,
                tsOut: tsOut,
                residense: residense
            };
            return [{
                id: 1,
                TrackLocations: [TrackLocations]
            }];
        }
        result = result.map(obj => {
            let tsIn = ctx.moment.utc(Number(obj.tsIn) * 1000).format('YYYY/MM/DD HH:mm:ss');
            let tsOut = ctx.moment.utc(Number(obj.tsOut) * 1000).format('YYYY/MM/DD HH:mm:ss');
            let residense = (new Date(tsOut).getTime() - new Date(tsIn).getTime()) / 1000;
            return {
                tagId: obj.tagId,
                devId: obj.devId,
                latitude: obj.location[1],
                longitude: obj.location[0],
                address: obj.address,
                inOut: obj.inOut,
                tsIn: tsIn,
                tsOut: tsOut,
                residense: residense
            };
        });
        /*
         * 轨迹分段
         */
        let data = {};
        let count = 0;
        for (let i = 0; i < result.length; i++) {
            //计算时间差
            if (i == 0 || (i > 0 && new Date(result[i].tsIn).getTime() - new Date(result[i - 1].tsIn).getTime() > 1000 * 60 * 60)) {
                //10分钟分段
                count++;
                if (!data[count]) {
                    data[count] = {
                        id: count,
                        TrackLocations: []
                    };
                    data[count]['TrackLocations'].push(result[i]);
                }
            }
            if ((i == 0 && result.length > 1) || (i > 0 && new Date(result[i].tsIn).getTime() - new Date(result[i - 1].tsIn).getTime() < 1000 * 60 * 60)) {
                data[count]['TrackLocations'].push(result[i]);
            }
        }
        return Object.values(data);
    }


    async getGpsLocationByTagId(options) {
        return this.getLocationByTagId(options)
    }
}

module.exports = GisService;